//
//  RJSwipeView.m
//  SwipeViewDemo
//
//  Created by 如佳 陈 on 15/8/12.
//  Copyright (c) 2015年 crj. All rights reserved.
//

#import "RJSwipeView.h"
#define TITLE_TAG_START 100
#define INDICATOR_HEIGHT 4

@interface RJSwipeView()<UIScrollViewDelegate>{
    NSLayoutConstraint *_topHeightConstraint;
    NSMutableDictionary *_hasOpenedDict;
    NSMutableArray *_labelsArray;
}

@end

@implementation RJSwipeView

#pragma mark - viewInit

- (instancetype)initWithFrame:(CGRect)frame
{
    self = [super initWithFrame:frame];
    if (self) {
        [self viewInit];
    }
    return self;
}

- (id)initWithCoder:(NSCoder *)aDecoder
{
    self = [super initWithCoder:aDecoder];
    if (self) {
        [self viewInit];
    }
    return self;
}

- (void)viewInit{
    [self addSubview:self.titlesView];
    [self addSubview:self.scrollView];
    
    [self setTopBackgroundColor:[UIColor clearColor]];
    self.topHeight = 44;
    
    self.titlesView.translatesAutoresizingMaskIntoConstraints = NO;
    self.scrollView.translatesAutoresizingMaskIntoConstraints = NO;
    NSDictionary *views = NSDictionaryOfVariableBindings(_titlesView, _scrollView);
    [self addConstraints:[NSLayoutConstraint constraintsWithVisualFormat:@"V:|-0-[_titlesView]-0-[_scrollView]-0-|" options:0 metrics:nil views:views]];
    
    _topHeightConstraint = [NSLayoutConstraint constraintWithItem:_titlesView attribute:NSLayoutAttributeHeight relatedBy:NSLayoutRelationEqual toItem:nil attribute:NSLayoutAttributeNotAnAttribute multiplier:1 constant:self.topHeight];
    [self setTopHeight:44];
    
    [self addConstraint:_topHeightConstraint];
    
    [self addConstraints:[NSLayoutConstraint constraintsWithVisualFormat:@"H:|-0-[_titlesView]-0-|" options:0 metrics:nil views:views]];

    [self addConstraints:[NSLayoutConstraint constraintsWithVisualFormat:@"H:|-0-[_scrollView]-0-|" options:0 metrics:nil views:views]];
    
    [[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(screenDidRotate:) name:UIDeviceOrientationDidChangeNotification object:nil];
    
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(.01 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
        self.selectedIndex = 0;
    });
}

- (void)dealloc{
    [[NSNotificationCenter defaultCenter] removeObserver:self];
}

#pragma mark - setter

- (void)setTopBackgroundColor:(UIColor *)topBackgroundColor{
    _topBackgroundColor = topBackgroundColor;
    self.titlesView.backgroundColor = _topBackgroundColor;
}

- (void)setTopHeight:(CGFloat)topHeight{
    _topHeight = topHeight;
}

#pragma mark - getter

- (UIView *)titlesView{
    if (!_titlesView) {
        _titlesView = [[UIView alloc]init];
        _titlesView.backgroundColor = self.topBackgroundColor;
        _titlesView.frame = CGRectMake(0, 0, self.frame.size.width, self.topHeight);
        _titlesView.autoresizingMask = UIViewAutoresizingFlexibleWidth;
    }
    return _titlesView;
}

- (UIView *)indicator{
    if (!_indicator) {
        _indicator = [[UIView alloc]init];
        _indicator.backgroundColor = self.tagBarTintColor;
    }
    return _indicator;
}

- (UIScrollView *)scrollView{
    if (!_scrollView) {
        _scrollView = [[UIScrollView alloc]init];
        _scrollView.pagingEnabled = YES;
        _scrollView.showsHorizontalScrollIndicator = NO;
        _scrollView.delegate = self;
        _scrollView.bounces = NO;
        
    }
    return _scrollView;
}

- (void)setTitles:(NSArray *)titles{
    _titles = titles;
    for (NSInteger i = 0; i < _titles.count; i++) {
        UILabel *label = [[UILabel alloc]init];
        label.text = _titles[i];
        label.tag = TITLE_TAG_START + i;
        label.userInteractionEnabled = YES;
        label.frame = CGRectMake(i * self.titlesView.frame.size.width/_titles.count, 0, self.titlesView.frame.size.width/_titles.count, self.topHeight);
        label.textAlignment = NSTextAlignmentCenter;
        label.textColor = self.tagBarTextColor;
        label.autoresizingMask = UIViewAutoresizingFlexibleWidth|UIViewAutoresizingFlexibleLeftMargin|UIViewAutoresizingFlexibleRightMargin;
        UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(titleTapAction:)];
        [label addGestureRecognizer:tap];
        if (self.selectedIndex == i) {
            label.textColor = self.tagBarTintColor;
        }
        if (!_labelsArray) {
            _labelsArray = [[NSMutableArray alloc]init];
        }
        [_labelsArray addObject:label];
        [self.titlesView addSubview:label];
    }
    
    self.indicator.translatesAutoresizingMaskIntoConstraints = NO;
    
    [self.titlesView addSubview:self.indicator];

    [self.titlesView addConstraint:[NSLayoutConstraint constraintWithItem:self.indicator attribute:NSLayoutAttributeLeft relatedBy:NSLayoutRelationEqual toItem:self.titlesView attribute:NSLayoutAttributeLeft multiplier:1 constant:0]];

    [self.titlesView addConstraint:[NSLayoutConstraint constraintWithItem:self.indicator attribute:NSLayoutAttributeBottom relatedBy:NSLayoutRelationEqual toItem:self.titlesView attribute:NSLayoutAttributeBottom multiplier:1 constant:0]];
    
    [self.titlesView addConstraint:[NSLayoutConstraint constraintWithItem:self.indicator attribute:NSLayoutAttributeHeight relatedBy:NSLayoutRelationEqual toItem:nil attribute:NSLayoutAttributeNotAnAttribute multiplier:1 constant:INDICATOR_HEIGHT]];
    
    [self.titlesView addConstraint:[NSLayoutConstraint constraintWithItem:self.indicator attribute:NSLayoutAttributeWidth relatedBy:NSLayoutRelationEqual toItem:self.titlesView attribute:NSLayoutAttributeWidth multiplier:(CGFloat)1/self.titles.count constant:0]];
}

- (void)setViewControllers:(NSArray *)viewControllers{
    _viewControllers = viewControllers;
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.1)), dispatch_get_main_queue(), ^{
        self.scrollView.contentSize = CGSizeMake(self.frame.size.width * _viewControllers.count, 0);
    });
    _hasOpenedDict = [[NSMutableDictionary alloc]init];
    for (NSInteger i = 0; i < _viewControllers.count; i++) {
        _hasOpenedDict[@(i)] = @(NO);
        
        UIView *view = ((UIViewController*)_viewControllers[i]).view;
        
        [self.scrollView addSubview:view];
        
        view.translatesAutoresizingMaskIntoConstraints = NO;
        
        [self.scrollView addConstraint:[NSLayoutConstraint constraintWithItem:view attribute:NSLayoutAttributeWidth relatedBy:NSLayoutRelationEqual toItem:self.scrollView attribute:NSLayoutAttributeWidth multiplier:1 constant:0]];
        
        [self.scrollView addConstraint:[NSLayoutConstraint constraintWithItem:view attribute:NSLayoutAttributeHeight relatedBy:NSLayoutRelationEqual toItem:self.scrollView attribute:NSLayoutAttributeHeight multiplier:1 constant:0]];
        
        if (i == 0) {
            [self.scrollView addConstraint:[NSLayoutConstraint constraintWithItem:view attribute:NSLayoutAttributeLeft relatedBy:NSLayoutRelationEqual toItem:self.scrollView attribute:NSLayoutAttributeLeft multiplier:1 constant:0]];
        }else{
            [self.scrollView addConstraint:[NSLayoutConstraint constraintWithItem:view attribute:NSLayoutAttributeLeft relatedBy:NSLayoutRelationEqual toItem:self.scrollView.subviews[i-1] attribute:NSLayoutAttributeRight multiplier:1 constant:0]];
        }
        
        [self.scrollView addConstraint:[NSLayoutConstraint constraintWithItem:view attribute:NSLayoutAttributeTop relatedBy:NSLayoutRelationEqual toItem:self.scrollView attribute:NSLayoutAttributeTop multiplier:1 constant:0]];
        
    }
}

- (void)setSelectedIndex:(NSUInteger)selectedIndex{
    _selectedIndex = selectedIndex;
    CGFloat offsetX = self.scrollView.contentSize.width * _selectedIndex/self.viewControllers.count;
    CGFloat offsetIndicatorX = self.scrollView.frame.size.width * _selectedIndex/self.viewControllers.count;
    [UIView animateWithDuration:.25 animations:^{
        self.scrollView.contentOffset = CGPointMake(offsetX,0);
        self.indicator.frame = CGRectMake(offsetIndicatorX, self.indicator.frame.origin.y, self.indicator.frame.size.width, self.indicator.frame.size.height);
    }];
    
    if (self.delegate && [self.delegate respondsToSelector:@selector(swipeView:didPresentViewController:firstPresented:)]) {
        [self.delegate swipeView:self didPresentViewController:self.viewControllers[_selectedIndex] firstPresented:![_hasOpenedDict[@(_selectedIndex)] boolValue]];
    }
    _hasOpenedDict[@(_selectedIndex)] = @(YES);

    for (NSInteger i = 0; i < _labelsArray.count; i++) {
        UILabel *label = _labelsArray[i];
        if (i == _selectedIndex) {
            label.textColor = self.tagBarTintColor;
        }else{
            label.textColor = self.tagBarTextColor;
        }
    }
}

#pragma mark - Action

- (void)titleTapAction:(UITapGestureRecognizer*)ges{
    self.selectedIndex = ges.view.tag - TITLE_TAG_START;
}

#pragma mark - Notifiaction

- (void)screenDidRotate:(NSNotification*)notification{
    self.scrollView.contentSize = CGSizeMake(self.frame.size.width * _viewControllers.count, 0);
    self.selectedIndex = self.selectedIndex;
}

#pragma mark - UIScrollView

- (void)scrollViewDidEndDecelerating:(UIScrollView *)scrollView{
    self.selectedIndex = scrollView.contentOffset.x/(self.scrollView.contentSize.width/self.viewControllers.count);
}

- (void)scrollViewDidScroll:(UIScrollView *)scrollView{
    CGFloat offsetIndicatorX = self.scrollView.frame.size.width * scrollView.contentOffset.x/scrollView.contentSize.width;
    self.indicator.frame = CGRectMake(offsetIndicatorX, self.indicator.frame.origin.y, self.indicator.frame.size.width, self.indicator.frame.size.height);
}

@end
